package com.ztorn.fiscale.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.ztorn.common.core.exception.file.InvalidExtensionException;
import com.ztorn.common.core.utils.DateUtils;
import com.ztorn.common.core.utils.StringUtils;
import com.ztorn.common.core.utils.file.MimeTypeUtils;
import com.ztorn.common.security.utils.SecurityUtils;
import com.ztorn.file.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.ztorn.fiscale.mapper.FiscaleDocumentMapper;
import com.ztorn.fiscale.mapper.FiscaleDocumentRelationMapper;
import com.ztorn.fiscale.domain.FiscaleDocument;
import com.ztorn.fiscale.service.IFiscaleDocumentService;

/**
 * 单证Service业务层处理
 *
 * @author ztorn
 */
@Service
public class FiscaleDocumentServiceImpl implements IFiscaleDocumentService
{
    /**
     * 默认的文档上传目录
     */
    private static final String DEFAULT_DOCUMENT_UPLOAD_PATH = "upload/document";

    /**
     * 文件访问域名
     */
    @Value("${file.domain:http://127.0.0.1:9300}")
    private String fileDomain;

    /**
     * 文件访问前缀
     */
    @Value("${file.prefix:/statics}")
    private String filePrefix;

    @Autowired
    private FiscaleDocumentMapper fiscaleDocumentMapper;

    @Autowired
    private FiscaleDocumentRelationMapper fiscaleDocumentRelationMapper;

    /**
     * 查询单证
     *
     * @param documentId 单证ID
     * @return 单证
     */
    @Override
    public FiscaleDocument selectFiscaleDocumentById(Long documentId)
    {
        return fiscaleDocumentMapper.selectFiscaleDocumentById(documentId);
    }

    /**
     * 查询单证列表
     *
     * @param fiscaleDocument 单证
     * @return 单证
     */
    @Override
    public List<FiscaleDocument> selectFiscaleDocumentList(FiscaleDocument fiscaleDocument)
    {
        return fiscaleDocumentMapper.selectFiscaleDocumentList(fiscaleDocument);
    }

    /**
     * 新增单证
     *
     * @param fiscaleDocument 单证
     * @return 结果
     */
    @Override
    public int insertFiscaleDocument(FiscaleDocument fiscaleDocument)
    {
        fiscaleDocument.setCreateTime(DateUtils.getNowDate());
        fiscaleDocument.setCreateBy(SecurityUtils.getUsername());
        return fiscaleDocumentMapper.insertFiscaleDocument(fiscaleDocument);
    }

    /**
     * 修改单证
     *
     * @param fiscaleDocument 单证
     * @return 结果
     */
    @Override
    public int updateFiscaleDocument(FiscaleDocument fiscaleDocument)
    {
        fiscaleDocument.setUpdateTime(DateUtils.getNowDate());
        fiscaleDocument.setUpdateBy(SecurityUtils.getUsername());
        return fiscaleDocumentMapper.updateFiscaleDocument(fiscaleDocument);
    }

    /**
     * 批量删除单证
     *
     * @param documentIds 需要删除的单证ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFiscaleDocumentByIds(Long[] documentIds)
    {
        // 删除单证关联
        for (Long documentId : documentIds)
        {
            fiscaleDocumentRelationMapper.deleteFiscaleDocumentRelationByDocumentId(documentId);
        }
        return fiscaleDocumentMapper.deleteFiscaleDocumentByIds(documentIds);
    }

    /**
     * 删除单证信息
     *
     * @param documentId 单证ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFiscaleDocumentById(Long documentId)
    {
        // 删除单证关联
        fiscaleDocumentRelationMapper.deleteFiscaleDocumentRelationByDocumentId(documentId);
        return fiscaleDocumentMapper.deleteFiscaleDocumentById(documentId);
    }

    /**
     * 上传单证文件
     *
     * @param file 文件
     * @param documentTypeId 单证类型ID
     * @param referenceNo 关联单号
     * @return 单证信息
     */
    @Override
    public FiscaleDocument uploadDocument(MultipartFile file, Long documentTypeId, String referenceNo)
    {
        try
        {
            // 上传文件
            String fileName = FileUploadUtils.upload(DEFAULT_DOCUMENT_UPLOAD_PATH, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);

            // 创建完整的文件访问URL
            String fullFileUrl = fileDomain + filePrefix + fileName;

            // 创建单证记录
            FiscaleDocument document = new FiscaleDocument();
            document.setDocumentName(file.getOriginalFilename());
            document.setDocumentTypeId(documentTypeId);
            document.setReferenceNo(referenceNo);
            document.setFileUrl(fullFileUrl);
            document.setFileType(getFileExtension(file.getOriginalFilename()));
            document.setFileSize(file.getSize());
            document.setUploadTime(new Date());
            document.setUploadBy(SecurityUtils.getUsername());
            document.setStatus("0");

            insertFiscaleDocument(document);

            return document;
        }
        catch (IOException | InvalidExtensionException e)
        {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    private String getFileExtension(String fileName)
    {
        if (StringUtils.isEmpty(fileName))
        {
            return "";
        }
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex < 0)
        {
            return "";
        }
        return fileName.substring(dotIndex + 1).toUpperCase();
    }
}
